package com.hmall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.FeignClientInter;
import com.hmall.common.client.FeignItemClient;
import com.hmall.common.dto.ResultDTO;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.OrderPaers;
import com.hmall.order.service.OrderService;
import com.hmall.user.pojo.Adderss;
import com.hmall.user.pojo.User;
import com.hmall.user.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private FeignItemClient itemClient;

    @Autowired
    private FeignClientInter feignClientInter;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Override
    public Long getOderRequset(OrderPaers paers) {

        Long itemId = paers.getItemId();

        Item item = itemClient.selectItemById(itemId);

        Long userId = ThreadLocalUtil.getUserId();


//        - 1）根据雪花算法生成订单id(mybatisplus自带)

//        - 2）商品微服务提供FeignClient，实现根据id查询商品的接口

//                - 3）根据itemId查询商品信息
//                - 4）基于商品价格、购买数量计算商品总价：totalFee
        Long totalFee = paers.getNum() * item.getPrice();
//                - 5）封装Order对象，初始status为未支付
        //初始化支付状态
        Order order = new Order();
        order.setStatus(1);
        order.setTotalFee(totalFee);
        order.setPaymentType(paers.getPaymentType());
        order.setUserId(userId);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
//                - 6）将Order写入数据库tb_order表中

        this.save(order);
//                - 7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail detail = new OrderDetail();

        detail.setOrderId(item.getId());

        detail.setItemId(item.getId());

        detail.setNum(Math.toIntExact(paers.getNum()));

        detail.setName(item.getName());

        detail.setPrice(item.getPrice());

        detail.setSpec("111-222-777");

        detail.setImage(item.getImage());

//        Item item = itemClient.selectItemById(paers.getAddressId());
        orderDetailMapper.insert(detail);
        //- 8）将user-service的根据id查询地址接口封装为FeignClient
        // - 9）根据addressId查询user-service服务，获取地址信息

        Adderss address = feignClientInter.getAddressById(paers.getAddressId());
        // - 10）将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setCreateTime(order.getCreateTime());
        orderLogistics.setUpdateTime(order.getUpdateTime());
        orderLogisticsMapper.insert(orderLogistics);
        //- 11）在item-service提供减库存接口，并编写FeignClient
        //- 12）调用item-service的减库存接口

        itemClient.reduceGoodsFrequency(order.getId(), paers.getNum());
        return order.getId();
    }

    //用户支付

    @Override
    public ResultDTO userLoginPayment(Long id, String password) {

        Order order = this.getById(id);

        if (order.getStatus() != 1) {
            throw new RuntimeException();
        }
        //获取用户id
        Long userId = ThreadLocalUtil.getUserId();
        //根据id查询用户信息
        User user = feignClientInter.findUserById(userId);
        //获取密码
        JSONObject jsonObject = JSONObject.parseObject(password);
        String password1 = jsonObject.getString("password");

        //对密码进行加密
        String pwd = DigestUtils.md5DigestAsHex(password1.getBytes());

        //判断密码是否正确

        if (pwd.equals(user.getPassword())) {
            long bs = user.getBalance() - order.getTotalFee();

            order.setStatus(2);

            //写入数据库
            itemClient.updateUser(userId, bs);
            //模拟支付

            this.saveOrUpdate(order);

            return new ResultDTO();
        }
        throw new RuntimeException("支付密码有问题!");
    }

    @Override
    public Order findOrderById(Long id) {
        Order detail = this.baseMapper.getOrderDetil(id);
        return detail;
    }

    @Override
    public List<Order> findOrderList(Integer status) {
        List<Order> orderList = this.baseMapper.findOrderLists(status);
        return orderList;
    }

    @Override
    public void updateStatus(Integer stats, Long id) {
        this.baseMapper.updateOrderStatus(stats, id);
    }

    //获取OrderDecil对象数据

    @Override
    public OrderDetail getOrderDetil(Long id) {
//        OrderDetail orderDetil = this.baseMapper.getOrderDetil(id);
        return null;
    }


}
